/*
 * @Author: szx
 * @Date: 2022-04-02 18:23:55
 * @LastEditTime: 2022-04-02 18:30:02
 * @Description:
 * @FilePath: \leetcode\剑指offerII\025\025.js
 */
function ListNode(val, next) {
    this.val = val === undefined ? 0 : val;
    this.next = next === undefined ? null : next;
}

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function (l1, l2) {
    const arr1 = [];
    while (l1) {
        arr1.push(l1.val);
        l1 = l1.next;
    }
    const arr2 = [];
    while (l2) {
        arr2.push(l2.val);
        l2 = l2.next;
    }
    let n1 = arr1.length - 1,
        n2 = arr2.length - 1,
        arr = [],
        add = 0;
    while (n1 >= 0 || n2 >= 0) {
        const x = n1 >= 0 ? arr1[n1] : 0;
        const y = n2 >= 0 ? arr2[n2] : 0;
        const res = x + y + add;
        arr.push(res % 10);
        add = Math.floor(res / 10);
        n1--;
        n2--;
    }
    if (add == 1) arr.push(1);
    const prev = new ListNode(-1);
    let cur = prev;
    for (let i = arr.length - 1; i >= 0; i--) {
        cur.next = new ListNode(arr[i]);
        cur = cur.next;
    }
    return prev.next;
};
